<?php
ini_set('display_errors',0);

define('APP_PATH','../Application/');
define('WEB_ROOT',dirname(__DIR__));

//加载通用常量配置
include_once APP_PATH.'Common/Conf/baseEnum.php';
//加载个性化常量配置
$localConfig=WEB_ROOT.'/data/local_specialConfig.php';
if(file_exists($localConfig)){
    include_once $localConfig;
}else{
    include_once APP_PATH.'Common/Conf/defaultConfig.php';
}



include('./wechat.class.php');

//回调地址
$backurl = $_GET['backurl'];
$scope = $_GET['scope'];
$code = $_GET['code'];

if(!$code) {
    if(!in_array($scope,array('base','userinfo'))) {
        die('scope错误');
    }
    //通过服务号的APPID进行授权
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
    $server= $protocol.$_SERVER['HTTP_HOST'];
    $redirect_uri =$server.$_SERVER['SCRIPT_NAME']."?backurl=".$backurl;

    $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.WX_APPID. '&redirect_uri=' .urlencode($redirect_uri). '&response_type=code&scope=snsapi_'.$scope.'&state=2#wechat_redirect';

    header ( "Location:" . $url );
    die;
}
else{
    $weixin = new wechatOauth(WX_APPID, WX_APPSECRET);
    $url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=".WX_APPID."&secret=".WX_APPSECRET."&code=".$code."&grant_type=authorization_code";
    $res = $weixin->https_request($url);
    $res = json_decode($res, true);
    var_dump($res);
    $row = $weixin->get_user_info($res);
    var_dump($row);
    if ($row['openid'] && $backurl) {
        $parms = http_build_query($row);
        header ( "Location:" . $backurl.'&'. $parms);
        die;
    }
}
